package com.qili.controller.zx;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.annotation.Bookmark;
import com.qili.base.controller.BaseController;
import com.qili.base.entity.BasePathConfig;
import com.qili.base.entity.CurrentUser;
import com.qili.base.service.BasePathConfigService;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.sys.SysUser;
import com.qili.entity.zx.ZxProject;
import com.qili.entity.zx.ZxProjectEvaluation;
import com.qili.entity.zx.ZxProjectEvaluationScore;
import com.qili.entity.zx.dto.ZxProjectEvaluationDTO;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.zx.ZxProjectEvaluationScoreService;
import com.qili.service.zx.ZxProjectEvaluationService;
import com.qili.service.zx.ZxProjectService;
import com.qili.util.*;
import com.spire.doc.FileFormat;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcBorders;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

import static java.util.Objects.isNull;

;
;
;

@Controller
@Slf4j
@RequestMapping("/zx/projectManager")
public class ZxEvaluationController extends BaseController  {

    @Autowired
    ZxProjectEvaluationService supervisorProjectEvaluationService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private BaseDictService baseDictService;
    @Autowired
    private ZxProjectService supervisorProjectService;
    @Autowired
    private ZxProjectEvaluationScoreService supervisorProjectEvaluationScoreService;
    @Autowired
    private SupervisorFileService supervisorFileService;
    @Autowired
    private ProjectNoticeServie  projectNoticeServie;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    private ZxPageOfficeController pageOfficeController;
    @Autowired
    private BaseCompanyService companyService;
    @Autowired
    private BasePathConfigService basePathConfigService;
    @Autowired
    private UploadUtil uploadUtil;

    /**
     *
     * @param model
     * @param request
     * @return
     */
    @GetMapping(value = "evaluation")
    @RequiresPermissions("zx:eval")
    public String Evaluation(Model model, HttpServletRequest request) {
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        //判断用户是否拥有质控角色    zkjsry
        boolean zk = subject.hasRole("zkjsry");
        CurrentUser user = CommonUtil.getUser();
        SysUser sysUser = userService.selectByPrimaryKey(user.getId());
        //当前用户的供需类型
        String gxType = sysUser.getGxType();
        return "/zx/evaluation/index";
    }
    @GetMapping("/evaluationForm")
    public String updateEvaluationForm(ZxProjectEvaluation evaluation){
        if(StringUtil.isNotBlank(evaluation.getCaseId())){
            String noticeId = evaluation.getCaseId();
            ProjectNotice notice = projectNoticeServie.selectByPrimaryKey(noticeId);
            /*是否查看过 1 已经查看 0  未查看*/
            notice.setIsView("1");
            notice.setModifyBy(CommonUtil.getUserId());
            notice.setModifyDate(DateUtil.getCurrentDateString());
            projectNoticeServie.updateByPrimaryKey(notice);
        }
        return "/zx/evaluation/form";
    }

    @GetMapping("/evaluationResult")
    public String getEvaluationResult(ZxProjectEvaluation evaluation, Model model){
        ZxProject supervisorProject = supervisorProjectService.selectByPrimaryKey(evaluation.getSpId());
        model.addAttribute("spId",evaluation.getSpId());
        model.addAttribute("spName",supervisorProject.getProjectName());
        return "/zx/evaluation/result";
    }

    @GetMapping("/eFormData")
    @ResponseBody
    public ReType getEvaluationFormData(ZxProjectEvaluation evaluation){
        ReType reType = new ReType();
        reType.setCode(-1);

        //根据条件获取需要显示的调查项目:
        //如果是评价实施人员或者供方,返回评价供方的调查项目
        String source = evaluation.getSource();
        Example example = new Example(BaseDict.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("badtTypecode",DictTypes.PJXM.getType());
        //source 001       aindex   1    代表评价实施人员
        //source 001       aindex   2    代表评价市场人员
        //source 003                     代表评价供方
        // 实施人员   ==   供方   使用一套调查项目        字典表中badt_
        if(("001".equals(source) && "1".equals(evaluation.getAindex())) || "003".equals(source)){
            criteria.andEqualTo("badtLevel1","1");
        }else if(("001".equals(source) && "2".equals(evaluation.getAindex()))){
            criteria.andEqualTo("badtLevel2","1");
        }
        example.setOrderByClause("badt_level3");
        List<BaseDict> baseDicts = baseDictService.selectByExample(example);
        //如果是评价市场人员的评价,返回评价市场人员的调查项目
        reType.setData(baseDicts);
        reType.setCode(0);
        return reType;
    }

    /**
     *根据spType查询三种状态的查询（0：待评价，1：已评价，空：全部）
     * @param supersiorProjectEvaluation
     * @return
     */
    @RequestMapping("evalistLevel")
    @ResponseBody
    public ReType getSupervisorProjectEvaluationLevel(ZxProjectEvaluationDTO supersiorProjectEvaluation, Model model, String page, String limit){
        ReType AlLevel= new ReType();
        try {
            //分页
            Page<ZxProjectEvaluationDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            //是否是质控管理人员:
            org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
            CurrentUser user = CommonUtil.getUser();
            SysUser sysUser = userService.selectByPrimaryKey(user.getId());
            //当前用户的供需类型
            String gxType = sysUser.getGxType();
            List<ZxProjectEvaluation> evaluationList = new ArrayList<>();
            supersiorProjectEvaluation.setSpeCreateBy(CommonUtil.getUserId());
            //拥有质控角色人员 和 公司高层可以对所有项目评价
            if(subject.hasRole("zkjsry")){
                //all设置为1,查询所有的项目
                supersiorProjectEvaluation.setAll("1");
            }
            if(subject.hasRole("gsgc")){
                //allToXmjl设置为1,对项目经理的评价,查询所有的项目
                supersiorProjectEvaluation.setAllToXmjl("1");
            }
            //只查项目状态为已完成的
            supersiorProjectEvaluation.setProjectStatus("004");
            if(supersiorProjectEvaluation.getSpType() != null && "0".equals(supersiorProjectEvaluation.getSpType())){
                evaluationList = supervisorProjectEvaluationService.selectListByUserIdNotFinished(supersiorProjectEvaluation);
            }else if(supersiorProjectEvaluation.getSpType() != null && "1".equals(supersiorProjectEvaluation.getSpType())){
                evaluationList = supervisorProjectEvaluationService.selectListByUserIdFinished(supersiorProjectEvaluation);
            }else{
                evaluationList = supervisorProjectEvaluationService.selectListByUserId(supersiorProjectEvaluation);
            }

//            List<ZxProjectEvaluationDTO> AlstData=supervisorProjectEvaluationService.selectListByType(supersiorProjectEvaluation);
//            AlLevel.setCount(tPage.getTotal());
            AlLevel.setCount(evaluationList.size());
            AlLevel.setData(evaluationList);
            AlLevel.setCode(0);
        } catch (NumberFormatException e) {
            AlLevel.setMsg("查询异常！！"+e.getMessage());
            AlLevel.setCode(1);
            e.printStackTrace();
        }
        return AlLevel;
    }


    @RequestMapping("/insertEvaluation")
    @ResponseBody
    public JsonUtil insertEvaluation(@RequestBody ZxProjectEvaluation supervisorProjectEvaluation){
        JsonUtil jsonUtil = new JsonUtil();
        //根据项目id获取项目数据:
        String spId = supervisorProjectEvaluation.getSpId();
        ZxProject supervisorProject = supervisorProjectService.selectByPrimaryKey(spId);
        //存入数据库:
        //存入表头:
        //对谁的评价?      source 001   aIndex  1  固定为对实施人员   对咨询项目经理的评价
        //                source 001   aIndex  2  固定为对市场人员   对项目发布人的评价
        //                source 003              固定为对供方       对咨询项目经理的评价
        String targetId = "";
        String type = "";
        if("003".equals(supervisorProjectEvaluation.getSource())
                || ("001".equals(supervisorProjectEvaluation.getSource()) && "1".equals(supervisorProjectEvaluation.getAindex()))){
            if(StringUtils.isBlank(supervisorProject.getProjectManagerPerson())){
                log.warn("评价时,没有找到该项目的项目经理");
                jsonUtil.setMsg("未知项目经理");
                jsonUtil.setFlag(false);
                return jsonUtil;
            }
            targetId = supervisorProject.getProjectManagerPerson();
            type = "1";
        }else if("001".equals(supervisorProjectEvaluation.getSource()) && "2".equals(supervisorProjectEvaluation.getAindex())){
            //查询项目的发布人：
            type = "2";
            String supProjectId = supervisorProject.getSupProjectId();
            if(StringUtils.isBlank(supProjectId)){
                log.warn("评价时,没有找到该项目对应的供需系统项目id");
                jsonUtil.setMsg("未知项目发布人");
                jsonUtil.setFlag(false);
                return jsonUtil;
            }
            SupplierProject supplierProject = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
            targetId = supplierProject.getPublishBy();
        }
        supervisorProjectEvaluation.setSpeTarget(targetId);
        supervisorProjectEvaluation.setSpeType(type);
        //判断
        ZxProjectEvaluation sameEvaluation = new ZxProjectEvaluation();
        sameEvaluation.setSpId(supervisorProjectEvaluation.getSpId());
        if(StringUtils.isNotBlank(supervisorProjectEvaluation.getCreateBy())){
            sameEvaluation.setCreateBy(supervisorProjectEvaluation.getCreateBy());
        }else{
            sameEvaluation.setCreateBy(CommonUtil.getUserId());
        }

        sameEvaluation.setSpeTarget(targetId);
        sameEvaluation.setSpeType(type);
        ZxProjectEvaluation dbSame = supervisorProjectEvaluationService.selectOne(sameEvaluation);
        if(dbSame != null){
            SupervisorFile file = new SupervisorFile();
            file.setLinkId(dbSame.getSpeId());
            SupervisorFile supervisorFile = supervisorFileService.selectOne(file);
            if(supervisorFile != null){
                jsonUtil.setMsg("已经提交过!");
                jsonUtil.setFlag(false);
                return jsonUtil;
            }else{
                supervisorProjectEvaluationService.deleteByPrimaryKey(dbSame.getSpeId());
            }
        }
        supervisorProjectEvaluationService.insertSelective(supervisorProjectEvaluation);
        List<ZxProjectEvaluationScore> scoreList = supervisorProjectEvaluation.getScoreList();
        for(ZxProjectEvaluationScore score:scoreList){
            if(null == score.getSpesScore()){
                continue;
            }
            score.setSpeId(supervisorProjectEvaluation.getSpeId());
            if(score.getSpesScore().contains(".")){
                score.setSpesScore( StringUtils.substring(score.getSpesScore(),0,score.getSpesScore().indexOf(".")+3));
            }
            supervisorProjectEvaluationScoreService.insertSelective(score);
        }
        jsonUtil.setData(supervisorProjectEvaluation);
        jsonUtil.setFlag(true);


        if(StringUtils.isNotBlank(supervisorProjectEvaluation.getAuto()) && "1".equals(supervisorProjectEvaluation.getAuto())){
            String bfcid = "";
            if("003".equals(supervisorProjectEvaluation.getSource()) || ("001".equals(supervisorProjectEvaluation.getSource()) && "1".equals(supervisorProjectEvaluation.getAindex()))){
                bfcid = "40022";
            }else if("001".equals(supervisorProjectEvaluation.getSource()) && "2".equals(supervisorProjectEvaluation.getAindex())){
                bfcid = "40023";
            }
            setEvaWord(supervisorProjectEvaluation,bfcid,"4",bfcid);
        }

        return jsonUtil;
    }



    /**
     * @Description:打开word 评价
     * @Date:21:12 2020/11/14
     */
    public void setEvaWord(ZxProjectEvaluation supervisorProjectEvaluation,String bfcid,String ft,String fpid) {
        try {
            int AiFt = Integer.valueOf(ft).intValue();
            FileEnum fileEnum = FileEnum.getEnumByType(AiFt);
            if (!isNull(fileEnum)) {
                //base_pathconfig 表ID 和
                if (StringUtil.isNotBlank(fpid)) {
                    fileEnum.setFilePathId(fpid);
                }
            }
            //根据参数获取实体类
            SysUser creator = userService.selectByPrimaryKey(supervisorProjectEvaluation.getCreateBy());
            String companyName = creator.getCompanyName();
            //根据该值去base_company表中查询一下:
            BaseCompany baseCompany = new BaseCompany();
            baseCompany.setBcId(companyName);
            BaseCompany baseCompany1 = companyService.selectByPrimaryKey(baseCompany);
            if (baseCompany1 != null && StringUtils.isNotBlank(baseCompany1.getBcName())) {
                creator.setCompanyName(baseCompany1.getBcName());
            }
            supervisorProjectEvaluation.setCreatorName(creator.getRealName());
            supervisorProjectEvaluation.setCreatorComName(creator.getCompanyName());

            BasePathConfig basePathConfig = basePathConfigService.selectByPrimaryKey(fileEnum.getFilePathId());

            if (!isNull(supervisorProjectEvaluation.getScoreList()) && (!isNull(basePathConfig))) {

                String AsPrjId = supervisorProjectEvaluation.getSpId();
                ZxProject supervisorProject = supervisorProjectService.selectByPrimaryKey(AsPrjId);
                String AsProjectName = supervisorProject.getProjectName();

                //查询该项目评价编号:
                ZxProjectEvaluation selectEvaluation = new ZxProjectEvaluation();
                selectEvaluation.setSpId(AsPrjId);
                int i = supervisorProjectEvaluationService.selectCount(selectEvaluation) +1;
                String s = StringUtil.autoGenericCode(i + "", 3);
                String bfcFilepath = basePathConfig.getBfcFilepath();
                bfcFilepath = bfcFilepath.replace("**项目",AsProjectName);
                StringBuffer saveFileName = new StringBuffer();
                saveFileName.append(uploadUtil.getUploadPath())
                        .append(File.separator)
                        .append(bfcFilepath)
                        .append(File.separator)
                        .append("满意度调查表_")
                        .append(s)
                        .append("_")
                        .append(DateUtil.getCurrentDateNoSpliter())
                        .append("_")
                        .append(AsProjectName)
                        .append(".doc");
                //需要打开的文件名
                String AsFileName = basePathConfig.getBfcTemplateFile();

                File copy = FileUtil.copy(AsFileName, saveFileName.toString(), false);

                String newFilePath = saveWordData(copy.getPath(),supervisorProjectEvaluation);

                SupervisorFile newFile = new SupervisorFile();
                File newSupFileOs = new File(newFilePath);
                newFile.setFileName(newSupFileOs.getName());
                newFile.setUrl(newSupFileOs.getPath());
                newFile.setDeleteState("1");
                newFile.setLinkId(supervisorProjectEvaluation.getSpeId());
                newFile.setCreateDate(new Date());
                newFile.setZskfileType("2");
                supervisorFileService.insertSelective(newFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String saveWordData(String filePath,ZxProjectEvaluation evaluation){
        //设置书签
        setBookMark(evaluation,filePath);
        String substring = filePath.substring(0, filePath.lastIndexOf("."));
        String newFilePath = substring + ".docx";
        docToDOcx(filePath,newFilePath);
        //设置表格内容
        setTableData(evaluation,newFilePath);
        //重新读取生成的文档
        clearTopRed(newFilePath);
        return newFilePath;
    }

    private void clearTopRed(String filePath){
        try {
            InputStream is = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os=new FileOutputStream(filePath);
            document.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * doc转docx
     * @param path
     * @param outPath
     * @return
     */
    public static void docToDOcx(String path,String outPath){
        com.spire.doc.Document dc = new com.spire.doc.Document();
        dc.loadFromFile(path);
        dc.saveToFile(outPath, FileFormat.Docx_2013);
        dc.close();
        File oldFile = new File(path);
        if(oldFile.exists()){
            oldFile.delete();
        }
    }


    private void setTableData(ZxProjectEvaluation evaluation,String filePath){
        try {
            List<ZxProjectEvaluationScore> scoreList = evaluation.getScoreList();
            int topRows = 2;
            FileInputStream in = new FileInputStream(filePath);
            XWPFDocument hwpf = new XWPFDocument(in);
            List<XWPFTable> tables = hwpf.getTables();//获取word中所有的表格
            XWPFTable table = null;
            if(CollectionUtil.isNotEmpty(tables)){
                table = tables.get(0);
            }

            if(table != null){
                List<XWPFTableRow> rows = table.getRows();

                XWPFTableRow row = table.getRow(0);
                XWPFTableRow last = table.getRow(2);
                List<XWPFTableCell> tableCells = row.getTableCells();
                for(int i=scoreList.size()-1;i>-1;i--){
                    int newRowInd = scoreList.size() - i + topRows -1;
                    ZxProjectEvaluationScore score = scoreList.get(i);
                    Integer scoreValue = 0;
                    if(StringUtils.isNotBlank(score.getSpesScore())){
                        scoreValue = Integer.valueOf(score.getSpesScore());
                    }
                    XWPFTableRow AxrNewRow = table.insertNewTableRow(newRowInd);
                    //复制样式
                    AxrNewRow.getCtRow().setTrPr(row.getCtRow().getTrPr());
                    //评价项目名称
                    XWPFTableCell AcNewcNo = AxrNewRow.addNewTableCell();

                    AcNewcNo.getCTTc().setTcPr(tableCells.get(1).getCTTc().getTcPr());
                    CTTcBorders ctTcBorders = AcNewcNo.getCTTc().getTcPr().addNewTcBorders();
                    CTBorder ctBorder = ctTcBorders.addNewLeft();
                    ctBorder.setVal(STBorder.Enum.forString("single"));
                    ctBorder.setSz(new BigInteger("1"));
                    BaseDict select = new BaseDict();
                    select.setBadtCode(score.getBdBadtCode());
                    select.setBadtTypecode(DictTypes.PJXM.getType());
                    List<BaseDict> select1 = baseDictService.select(select);
                    setCellText(AcNewcNo, select1.get(0).getBadtName());
                    //90-100
                    XWPFTableCell cell100 = AxrNewRow.addNewTableCell();
                    cell100.getCTTc().setTcPr(tableCells.get(1).getCTTc().getTcPr());
                    cell100.getParagraphs().get(0).getCTP().setPPr(tableCells.get(1).getParagraphs().get(0).getCTP().getPPr());
                    if(scoreValue >= 90 && scoreValue <= 100){
                        setCellText(cell100, scoreValue+"");
                    }else{
                        setCellText(cell100, "");
                    }

                    //80-89
                    XWPFTableCell cell90 = AxrNewRow.addNewTableCell();
                    cell90.getCTTc().setTcPr(tableCells.get(2).getCTTc().getTcPr());
                    cell90.getParagraphs().get(0).getCTP().setPPr(tableCells.get(2).getParagraphs().get(0).getCTP().getPPr());
                    if(scoreValue >= 80 && scoreValue <= 89){
                        setCellText(cell90, scoreValue+"");
                    }else{
                        setCellText(cell90, "");
                    }
                    //60-79
                    XWPFTableCell cell80 = AxrNewRow.addNewTableCell();
                    cell80.getCTTc().setTcPr(tableCells.get(3).getCTTc().getTcPr());
                    cell80.getParagraphs().get(0).getCTP().setPPr(tableCells.get(3).getParagraphs().get(0).getCTP().getPPr());
                    cell80.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                    if(scoreValue >= 60 && scoreValue <= 79){
                        setCellText(cell80, scoreValue+"");
                    }else{
                        setCellText(cell80, "");
                    }
                    //0-59
                    XWPFTableCell cell59 = AxrNewRow.addNewTableCell();
                    cell59.getCTTc().setTcPr(tableCells.get(4).getCTTc().getTcPr());
                    cell59.getParagraphs().get(0).getCTP().setPPr(tableCells.get(4).getParagraphs().get(0).getCTP().getPPr());
                    if(scoreValue >= 0 && scoreValue <= 59){
                        setCellText(cell59, scoreValue+"");
                    }else{
                        setCellText(cell59, "");
                    }
                    //备注
                    XWPFTableCell note = AxrNewRow.addNewTableCell();
                    note.getCTTc().setTcPr(tableCells.get(5).getCTTc().getTcPr());
                    note.getParagraphs().get(0).getCTP().setPPr(tableCells.get(5).getParagraphs().get(0).getCTP().getPPr());
                    setCellText(note, "");
                }

                FileOutputStream out = new FileOutputStream(filePath);
                hwpf.write(out);
                out.close();

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setBookMark(ZxProjectEvaluation evaluation, String filePath){
        try {
            Map<String,String> dataMap = getEvaluationBookmarkToMap(evaluation);
            FileInputStream in = new FileInputStream(filePath);
            HWPFDocument hwpf = new HWPFDocument(in);//得到word文档的信息
            Bookmarks bookmarks = hwpf.getBookmarks();

            for(int dwI = 0;dwI < bookmarks.getBookmarksCount();dwI++){
                org.apache.poi.hwpf.usermodel.Bookmark bookmark = bookmarks.getBookmark(dwI);

                if(dataMap.containsKey(bookmark.getName())){
                    Range range = new Range(bookmark.getStart(),bookmark.getEnd(),hwpf);
                    range.replaceText(dataMap.get(bookmark.getName()),false);
                }
            }
            FileOutputStream out = new FileOutputStream(filePath);
            hwpf.write(out);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 把对象书签值提取为map
     * @param evaluation
     * @return
     */
    private Map getEvaluationBookmarkToMap(ZxProjectEvaluation evaluation){
        //获取所有属性
        Map bookmarkMap = new HashMap<String,String>();
        List<Field> properties = ClassUtils.getBookmarkFields(ZxProjectEvaluation.class, true);
        for (int i = 0, len = properties.size(); i < len; i++) {
            Field AfdTmp = properties.get(i);
            Bookmark bk = AfdTmp.getAnnotation(Bookmark.class);
            String mark = bk.mark();
            String AsFieldValue = null;
            try {
                AsFieldValue = (String) AfdTmp.get(evaluation);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (StringUtils.isNotBlank(AsFieldValue)) {
                bookmarkMap.put(mark,AsFieldValue);
            }else{
                if("PO_creatorComName".equals(mark)){
                    bookmarkMap.put(mark,"未知");
                }
            }
        }
        bookmarkMap.put("PO_year",DateUtil.getCurrentYear());
        bookmarkMap.put("PO_month",DateUtil.getCurrentMonth());
        return bookmarkMap;
    }



    private static void setCellText(XWPFTableCell pCell, String pCellText) {
        List<XWPFParagraph> AlstPara = pCell.getParagraphs();
        if (AlstPara.size() > 0) {
            List<XWPFRun> AlstRuns = AlstPara.get(0).getRuns();
            if (AlstRuns.size() > 0) {
                AlstRuns.get(0).setText(pCellText, 0);
            } else {
                AlstPara.get(0).createRun().setText(pCellText, 0);
            }
        } else {
            pCell.setText(pCellText);
        }
    }



    /**
     * 查询评价列表
     * @param evaluation
     * @return
     */
    @RequestMapping("/tagList")
    @ResponseBody
    public ReType selectEvaluationList(ZxProjectEvaluation evaluation, String page, String limit){
        List<ZxProjectEvaluation> evaluationList = null;
        Page<ZxProjectEvaluation> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        evaluation.setSpeTarget(CommonUtil.getUserId());
        evaluationList = supervisorProjectEvaluationService.selectSomeTargetEvaList(evaluation);

        if(evaluationList.size() > 0){
            for(ZxProjectEvaluation evaluation1 : evaluationList){
                ReType reType = selectEvaluationResultList(evaluation1);
                List<ZxProjectEvaluationScore> resultList = (List<ZxProjectEvaluationScore>)reType.getData();
                ZxProjectEvaluationScore o = resultList.get(resultList.size() - 1);
                evaluation1.setScore(o.getOne());
            }
        }
        return new ReType(tPage.getTotal(),evaluationList);
    }

    /**
     * 对自己的 某个项目的  评价统计结果表
     */
    @RequestMapping("/tagResultList")
    @ResponseBody
    public ReType selectEvaluationResultList(ZxProjectEvaluation evaluation){
        ReType reType = new ReType();
        evaluation.setSpeTarget(CommonUtil.getUserId());
        List<ZxProjectEvaluationScore> checkedBadtCodeList = supervisorProjectEvaluationScoreService.selectCheckedList(evaluation);
        List<ZxProjectEvaluationScore> resultList = new ArrayList<ZxProjectEvaluationScore>();
        if(checkedBadtCodeList != null && checkedBadtCodeList.size() > 0){
            for(ZxProjectEvaluationScore score : checkedBadtCodeList){
                score.setSpId(evaluation.getSpId());
                score.setSpeTargetUserId(CommonUtil.getUserId());
                ZxProjectEvaluationScore aScore = supervisorProjectEvaluationScoreService.selectTargetEvaluationScoreResultOneNode(score);
                if(score != null){
                    resultList.add(aScore);
                }
            }
        }
        calAvg(resultList);
        reType.setData(resultList);
        reType.setCode(0);
        return reType;
    }

    private void calAvg(List<ZxProjectEvaluationScore> scoreList){
        BigDecimal avg = BigDecimal.ZERO;
        if(scoreList.size() > 0){
            for(ZxProjectEvaluationScore score : scoreList){
                if(score.getAvgScore() != null){
                    avg = avg.add(new BigDecimal(score.getAvgScore()));
                }
            }
            avg = avg.divide(new BigDecimal(scoreList.size()+""),2,BigDecimal.ROUND_HALF_UP);
        }
        ZxProjectEvaluationScore lastLine = new ZxProjectEvaluationScore();
        lastLine.setBdBadtName("总平均分");
        lastLine.setOne(avg.toString());
        scoreList.add(lastLine);
    }

}
